package com.ayoka.base;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.ayoka.R;
import com.jcp.baselibrary.model.ToolBarOptions;
import com.jcp.baselibrary.networkstate.NetInfo;
import com.jcp.baselibrary.networkstate.NetWorkEvent;
import com.jcp.baselibrary.utils.MyLogger;
import com.jcp.baselibrary.utils.SnackBarUtil;
import com.jcp.baselibrary.utils.StatusBarUtil;
import com.jcp.baselibrary.utils.StatusBarUtils;
import com.jcp.baselibrary.utils.TDevice;
import com.jcp.baselibrary.utils.ToastUtil;
import com.jcp.baselibrary.utils.UIUtils;

import java.util.Observable;
import java.util.Observer;


/**
 * =========================================================
 * @ProjectName: 
 * @ClassName: BaseActivity
 * @Description: 作用描述
 * @Author: jincp
 * @CreateDate: 2019/3/14 13:48
 * =========================================================
 */
public abstract class BaseActivity<VDB extends ViewDataBinding, P extends BasePresenter> extends AppCompatActivity implements IBaseView, View.OnClickListener, Observer {

    public static final int REQUEST_CODE_FOR_RESULT = 0x999;
    public static final int REQUEST_CODE_FOR_REFRESH = 0x998;


    protected String TAG = getClass().getSimpleName();
    protected VDB mDataBinding;
    protected P mPresenter;

    /**
     * 加载对话框
     */
    public DialogLoading dialogLoading;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyLogger.d(TAG, "onCreate");
        NetWorkEvent.getInstance().addObserver(this);
        onBeforeSetContentLayout();
        configIntentValue();
        if (getContentLayout() != 0) {
            mDataBinding = DataBindingUtil.setContentView(this, getContentLayout());
        }
        mPresenter = getPresenter();
        if (mPresenter != null) {
            mPresenter.attach(this);
        }
        initViews();
        initData(savedInstanceState);
    }

    protected abstract int getContentLayout();

    protected abstract void initViews();

    protected abstract void initData(Bundle savedInstanceState);

    protected abstract P getPresenter();

    protected void onBeforeSetContentLayout() {
        StatusBarUtils.setStatusBar(this, false, false);
        StatusBarUtils.setStatusTextColor(this, true);
    }

    protected void setCustomToolBar(Toolbar toolBar, ToolBarOptions options) {
        if (toolBar == null || options == null) return;
        setSupportActionBar(toolBar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        if (options.logoId != 0) {
            toolBar.setLogo(options.logoId);
        }
        if (options.backgroundResource != 0) {
            toolBar.setBackgroundResource(options.backgroundResource);
        }
        if (options.navigateId != 0) {
            toolBar.setNavigationIcon(options.navigateId);
            // 这里要注意的就是需要将setSupportActionBar(toolbar)放在setNavigationOnClickListener()之前设置才行。
            toolBar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });
        } else {
            toolBar.setNavigationIcon(null);
        }
        TextView tv_back = (TextView) findViewById(R.id.toolbar_back_title);
        if (tv_back != null && !TextUtils.isEmpty(options.backString)) {
            tv_back.setText(options.backString);
            tv_back.setTextColor(options.titleColor);
            tv_back.setVisibility(View.VISIBLE);
            tv_back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });
        }
        // 这里要注意的就是需要将title标题 setSupportActionBar(toolbar)放在之前设置才行。
        TextView tv_title = (TextView) findViewById(R.id.toolbar_title);
        if (tv_title != null && !TextUtils.isEmpty(options.titleString)) {
            tv_title.setText(options.titleString);
            tv_title.setTextColor(options.titleColor);
            if (options.titleGravity == Gravity.LEFT) {
                Toolbar.LayoutParams params = (Toolbar.LayoutParams) tv_title.getLayoutParams();
                params.gravity = Gravity.CENTER_VERTICAL;
                if (options.navigateId == 0) {
                    params.setMargins(toolBar.getContentInsetStartWithNavigation(), 0, 0, 0);
                }
                tv_title.setLayoutParams(params);
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        configIntentValue();
    }

    protected void configIntentValue() {
    }

    /**
     * 显示加载对话框 默认使用R.string.loading
     *
     * @return 返回一个加载对话框
     */
    public void showWaitDialog() {
       showWaitDialog(UIUtils.getString(R.string.loading));
    }

    /**
     * 显示加载对话框
     *
     * @param message 文字显示信息
     * @return 返回一个加载对话框
     */
    @Override
    public void showWaitDialog(String message) {
        if (isFinishing()) return;
        try {
            hideWaitDialog();
            if (dialogLoading == null) {
                dialogLoading = new DialogLoading.Builder()
                        .setAnimation(0)
                        .setMessage(message)
                        .build();
            }
            dialogLoading.show(getSupportFragmentManager(), "DialogLoading");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 隐藏加载对话框
     */
    @Override
    public void hideWaitDialog() {
        if (isFinishing()) return;
        if (dialogLoading != null) {
            try {
                dialogLoading.dismissAllowingStateLoss();
                dialogLoading = null;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * 显示提示框
     *
     * @param content 文字显示content
     */
    @Override
    public void showToast(String content) {
        ToastUtil.getInstance().show(content);
    }

    /**
     * 显示SnackBar
     *
     * @param content 文字显示content
     * @param type
     */
    @Override
    public Snackbar showSnackBar(View view, String content, int type) {
        Snackbar snackbar = SnackBarUtil.make(view, content, type, Snackbar.LENGTH_SHORT);
        snackbar.show();
        return snackbar;
    }

    @Override
    public void onClick(View view) {
        TDevice.hideSoftKeyboard(view);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        hideWaitDialog();
        NetWorkEvent.getInstance().deleteObserver(this);
        if (mPresenter != null) {
            mPresenter.detachView();
            mPresenter = null;
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        if (observable instanceof NetWorkEvent) {
            NetInfo netInfo = (NetInfo) data;
            onNetworkState(netInfo.isNetworkAvailable, netInfo);
        }
    }

    /**
     * 网络状态
     *
     * @param isNetworkAvailable 网络是否可用
     * @param netInfo            网络信息
     */
    public void onNetworkState(boolean isNetworkAvailable, NetInfo netInfo) {
        MyLogger.d(TAG, "onNetworkState" + netInfo.networkType);
        if (isNetworkAvailable) {
//            showToast(R.string.network_is_available);
        } else {
            showToast(UIUtils.getString(R.string.network_is_not_available));
        }
    }

    public void finishDelay(){
        if (isFinishing()) return;
        UIUtils.postTaskDelay(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, 2000);
    }
}
